#include "ProfilerGP2X.h"


CProfilerGP2X::CProfilerGP2X(void)
{
}

CProfilerGP2X::~CProfilerGP2X(void)
{
}

bool CProfilerGP2X::init(void)
{

	return true;
}

void CProfilerGP2X::startApplication(void)
{
	m_allApplication.startTime = SDL_GetTicks();
	m_allApplication.numberOfExecution = 1;
	m_allApplication.executionTime=0;
}

void CProfilerGP2X::endApplication(void)
{
	//get the final time
	m_allApplication.endTime = SDL_GetTicks();

	//add the execution time
	m_allApplication.executionTime = m_allApplication.endTime - m_allApplication.startTime;
}

void CProfilerGP2X::startCount(const string& name)
{
	//check if the entry alrady exist
	for(map<string, timeStruct>::iterator i = m_timeMap.begin(); i!=m_timeMap.end(); i++)
	{
		if(i->first.compare(name)==0) //if it exist
		{
			//get the new start time
			i->second.startTime = SDL_GetTicks();

			//increase the number of execution
			i->second.numberOfExecution++;
			return;
		}
	}

	//it doesn't exist so we create it in the map
	timeStruct newTimeStruct;
	newTimeStruct.endTime=0;
	newTimeStruct.startTime=0;
	newTimeStruct.numberOfExecution=1;
	newTimeStruct.executionTime=0;


	//add an entry in the map
	m_timeMap[name]=newTimeStruct;

	//get the start time
	m_timeMap[name].startTime = SDL_GetTicks();
	
}

void CProfilerGP2X::endCount(const string& name)
{
	for(map<string, timeStruct>::iterator i = m_timeMap.begin(); i!=m_timeMap.end(); i++)
	{
		if(i->first.compare(name)==0) 
		{
			i->second.endTime = SDL_GetTicks();
			i->second.executionTime+=i->second.endTime - i->second.startTime;
			return;
		}
	}
}

void CProfilerGP2X::write(void)
{
	//display the time of the total application
	Uint32 applicationRealTime = m_allApplication.executionTime;
	printf("Overall : %d \n", applicationRealTime);

	//display info about functions
	for(map<string, timeStruct>::iterator i = m_timeMap.begin(); i!=m_timeMap.end(); i++)
	{
		//display the name of the function
		printf(i->first.c_str());

		//calculate the time
		Uint32 realTime = i->second.executionTime;

		//display time
		printf(" : %d \n", realTime);

		//calculate percentage
		double percent = ((float)realTime/(float)applicationRealTime)*100;

		//display percentage
		printf("    - Percentage of total execution = %5.3f\n", percent);

		//display number of calls
		printf("    - Number of call : %d\n", i->second.numberOfExecution);

	}
}
